/* eslint-disable react-hooks/exhaustive-deps */
/*
 * @Author: zy
 * @Date: 2021-10-21 10:35:47
 * @Last Modified by: lt
 * @Last Modified time: 2021-10-27 15:37:14
 */

import React, { useState, useEffect } from 'react';
import { Modal, Button, Space, Form, Input, Upload, message } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { saveUser, checkPhone, deleteFile } from '@/services/user';
import type { OptionUserInfoDataType } from '@/services/user';
import { getToken, serverUrl } from '@/utils/utils';
import type { UploadFile } from 'antd/lib/upload/interface';

type PropsType = {
  modalVisible: boolean;
  hideModal: () => void;
  resetModifyAid: () => void;
  dataSource: OptionUserInfoDataType | undefined;
  modifyAid: number;
};

const UserManageModal = ({
  modalVisible,
  hideModal,
  dataSource,
  modifyAid,
  resetModifyAid,
}: PropsType) => {
  const [form] = Form.useForm(); // 表单对象
  const [modalTitle, setModalTitle] = useState('新增'); //设置modal标题
  const [isDisable, setIsDisable] = useState(false); //设置提交按钮是否可用
  const [loading, setLoading] = useState(false); //设置确认按钮的loading
  const [enclosureId, setEnclosureId] = useState<string>();
  const [fileList, setFileList] = useState<UploadFile[]>();

  //表单格式
  const Layout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 16 },
  };

  /**
   * @description: 表单初始化(根据option值是否变化：1、渲染modal数据；2、判断modal标题)
   */
  useEffect(() => {
    let mounted = true;
    if (mounted) {
      //Do Something
      if (dataSource) {
        // const { name, phone, password,enclosureId,enclosureName } = dataSource.data;
        const data = dataSource.data;
        const { name, phone, password } = data;
        if (data.enclosureId) {
          const file = {
            name: data.enclosureName,
            uid: data.enclosureId,
          };
          setEnclosureId(file.uid);
          setFileList([file]);
        } else {
          setEnclosureId(undefined);
          setFileList(undefined);
        }
        form.setFieldsValue({ name, phone, password });
      } else {
        form.resetFields();
        setEnclosureId(undefined);
        setFileList(undefined);
      }
      setModalTitle(modifyAid === -1 ? '新增图书' : '修改图书');
    }
    return function cleanup() {
      mounted = false;
    };
  }, [modifyAid]);

  /**
   * @description: 校验手机号码（1、传入数据通过接口传给后端；
   *                            2、根据返回的数据判别手机号是否存在和数据是否渲染
   *                            3、信息提示）
   */

  const CheckPhone = async (event: any) => {
    const params = { aid: modifyAid, phone: event.target.value };
    const msg = await checkPhone(params);
    if (msg?.code === 10000) {
      const { isExists } = msg.data;
      if (isExists) {
        if (modifyAid === -1) {
          const userInfo = msg.data.userInfo;
          form.setFieldsValue({
            name: userInfo.name,
            phone: userInfo.phone,
            password: userInfo.password,
          });
          if (userInfo.enclosureId) {
            setEnclosureId(userInfo.enclosureId);
            const file = {
              name: userInfo.enclosureName,
              uid: userInfo.enclosureId,
            };
            setEnclosureId(file.uid);
            setFileList([file]);
          }
        }
        setIsDisable(true);
        message.error('手机号已存在，请修改！');
      } else {
        setIsDisable(false);
      }
    } else {
      message.error(msg ? msg.message : '校验失败');
    }
  };

  /**
   * @description: 表单提交(传入数据，调用接口保存表单数据并做信息提示)
   */
  const finishHandler = async (value: any) => {
    setLoading(true);
    const { name, phone, password } = value;
    const body = {
      aid: modifyAid,
      name,
      phone,
      password,
      enclosureId,
    };
    const msg = await saveUser(body);
    if (msg?.code === 10000) {
      setTimeout(() => {
        message.success('提交成功');
        hideModal();
      }, 200);
    } else {
      message.error(msg ? msg.message : '提交失败');
    }
    setLoading(false);
    resetModifyAid();
  };

  /**
   * @description: 从后端获取返回的附件id
   */
  const fileChangeHandler = (file: any) => {
    if (file.file.status === 'done') {
      const msg = file.file.response;
      setEnclosureId(msg.data.enclosureId);
    }
  };

  const removeFile = async () => {
    if (enclosureId) {
      const params = { enclosureId };
      const msg = await deleteFile(params);
      if (msg.code === 10000) {
        message.success('文件已移除');
        setEnclosureId(undefined);
        setFileList(undefined);
        return true;
      } else {
        return false;
      }
    } else {
      setFileList(undefined);
    }
    return false;
  };

  //异步函数：用于新增modal手动关闭时表单和文件的重置（删除）
  const onCancel = async () => {
    if (modifyAid === -1) {
      if (enclosureId) {
        const params = { enclosureId };
        const msg = await deleteFile(params);
        if (msg.code === 10000) {
          setEnclosureId(undefined);
          setFileList(undefined);
          form.resetFields();
          hideModal();
        }
      } else {
        form.resetFields();
        hideModal();
      }
    } else {
      hideModal();
    }
    resetModifyAid();
  };

  return (
    <div>
      <Modal
        forceRender
        getContainer={false}
        width={649}
        title={modalTitle}
        visible={modalVisible}
        onCancel={onCancel}
        footer={
          <Space>
            <Button onClick={onCancel}>取消</Button>
            <Button
              type="primary"
              disabled={isDisable}
              loading={loading}
              onClick={() => form.submit()}
            >
              确定
            </Button>
          </Space>
        }
      >
        <Form {...Layout} layout="horizontal" form={form} onFinish={finishHandler}>
          <Form.Item
            name="name"
            key="name"
            label="姓名："
            validateTrigger="onBlur"
            rules={[
              { required: true, message: '请输入姓名' },
              { max: 16, type: 'string', message: '用户姓名最长为16个字符' },
            ]}
          >
            <Input placeholder="请输入" allowClear={true} key="name" />
          </Form.Item>
          <Form.Item
            name="phone"
            key="phone"
            label="手机号码："
            validateTrigger="onBlur"
            rules={[
              { required: true, message: '请输入手机号' },
              { pattern: new RegExp(/^\d{11}$/, 'g'), message: '手机号必须为11位数字' },
            ]}
          >
            <Input
              placeholder="请输入"
              allowClear={true}
              key="phone"
              onBlur={(e) => CheckPhone(e)}
            />
          </Form.Item>
          <Form.Item
            name="password"
            key="password"
            label="密码："
            validateTrigger="onBlur"
            rules={[
              { required: true, message: '请输入密码' },
              {
                pattern: new RegExp(/^(?=.*\d)(?=.*[a-zA-Z]).{6,20}$/, 'g'),
                message: '密码为6-20个字符，由数字 + 字母组成',
              },
            ]}
          >
            <Input.Password placeholder="请输入" allowClear={true} key="password" />
          </Form.Item>
          <Form.Item label="上传附件：">
            <Upload
              action={`${serverUrl()}/userManage/uploadFile`}
              headers={{ token: getToken() }}
              onChange={(file) => fileChangeHandler(file)}
              onRemove={removeFile}
              maxCount={1}
              fileList={fileList}
              onDownload={() => {}}
            >
              <Button icon={<UploadOutlined />} key="upload">
                Upload
              </Button>
            </Upload>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default UserManageModal;
